import React, { useEffect, useState, useRef } from 'react'
import { Tabs, Swiper } from 'antd-mobile'

import styles from './index.module.css'
import { useNavigate, useLocation } from 'react-router-dom'

import Winnow from '../winnow'
import PersonalCare from '../personalCare'

import PubSub from 'pubsub-js'
import { ACTION_USER_NAME } from '../../pubSub/constant'

import { getHomeData } from '../../axiosRequest/api2'



function Home() {
    const [activeIndex, setActiveIndex] = useState(0)
    const ref = useRef(null)

    let { pathname } = useLocation();

    let navigate = useNavigate()


    const tabItems = [{ key: 'winnow', title: '精选' }, { key: 'personalCare', title: '个人洗护' },

    ]


    //[]空数组相当于componentDidMount
    useEffect(() => {
        //用户刷新或者点击后退的时候或者首页进来的时候 保证tab指示条的准确性
        if (pathname.indexOf("winnow") !== -1) {
            const index = tabItems.findIndex(item => item.key === "winnow")
            setActiveIndex(index)
        } else if (pathname.indexOf("personalCare") !== -1) {
            const index = tabItems.findIndex(item => item.key === "personalCare")
            setActiveIndex(index)
        }


        const obj1 = new Map();
        getHomeData(obj1)
            .then(response => {
                const data = response.data;
                console.log('getHomeData>', data);
            })
            .catch(error => {
                console.log('getHomeData-error>', error);
                console.log(error);
            });

        return () => {

        }
    }, [pathname]);

    function onTabChange(key) {
        //方法一
        for (let i = 0; i < tabItems.length; i++) {
            let item = tabItems[i];
            if (item.key === key) {
                setActiveIndex(i)
                ref.current.swipeTo(i)
                PubSub.publish(ACTION_USER_NAME, i);
                //navigate(item.key,{ replace: true, state: { item: item } })
                return
            }
        }
        //方法二
        // const index = tabItems.findIndex(item => item.key === key)
        // setActiveIndex(index)
    }


    //渲染组件
    return (<div className={styles.home_container}>
        <Tabs activeKey={tabItems[activeIndex].key} onChange={onTabChange}>
            {tabItems.map(item => (<Tabs.Tab title={item.title} key={item.key} />))}
        </Tabs>
        <Swiper ref={ref} style={{ "--height": '100vh' }} allowTouchMove={false} indicator={() => null}>
            <Swiper.Item key={0}>
                <Winnow />
            </Swiper.Item>
            <Swiper.Item key={1}>
                <PersonalCare />
            </Swiper.Item>
        </Swiper>
    </div>)
}

export default Home;
